import { invmbInvmabVoList } from '@/api/url/base';
import { selectInvmaHeadVoTreeList } from '@/api/url/scheduling';
import { isNullPm } from '@/utils/baseMethods';
import { onMounted, reactive, watch, ref, computed } from 'vue';
import { VXETable } from 'vxe-table';
import XEClipboard from 'xe-clipboard';

export default function importConfig() {
  const base = reactive<any>({
    queryInfo: null,
    id: null,
    maType: null,
    topTwo: null,
    name: null,
    shortcutCode: null,
    specification: null,
    quickQuery: null,
    baseDom: null,
    tabelDom: null,
    pagination: {
      current: 1,
      pageSize: 20,
      total: 0,
    },
    searchKey: '',
    originTreeData: [],
    tableRef: null,
    selectedRowKeys: null,
    selectionRows: [],
    type: '1',
    quickQueryTip: '请输入品名/品号/规格',
  });

  //获取所有品类
  const getAllClasses = () => {
    selectInvmaHeadVoTreeList().then((res: any) => {
      if (res.code == '200') {
        base.originTreeData = [{ title: '全部', key: '' }];
        let obj1;
        let obj2;
        res.data.tree.forEach((item1) => {
          obj1 = {
            title: item1.ma003,
            key: item1.ma002,
            children: [],
          };
          item1.head.forEach((item2) => {
            obj2 = {
              title: item2,
              key: item2 + '-' + item1.ma002,
              head: item1.ma002,
            };
            obj1.children.push(obj2);
          });
          base.originTreeData.push(obj1);
        });
      }
    });
  };

  const treeData = computed(() => {
    if (!base.searchKey) return base.originTreeData;
    return searchData(base.searchKey);
  });

  function searchData(keyword) {
    const loop = (data) => {
      const result = [];
      data.forEach((item) => {
        if (item.title.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
          result.push({ ...item });
        } else if (item.children) {
          const filterData = loop(item.children);
          if (filterData.length) {
            result.push({
              ...item,
              children: filterData,
            });
          }
        }
      });
      return result;
    };

    return loop(base.originTreeData);
  }

  function getMatchIndex(title) {
    if (!base.searchKey) return -1;
    return title.toLowerCase().indexOf(base.searchKey.toLowerCase());
  }

  const menuConfig = reactive({
    className: 'my-menus',
    header: {
      options: [[{ code: 'exportAll', name: '导出所有.csv' }]],
    },
    body: {
      options: [
        [{ code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' }],
        [
          { code: 'remove', name: '删除', prefixIcon: 'vxe-icon-delete-fill color-red' },
          {
            name: '筛选',
            children: [
              { code: 'clearFilter', name: '清除筛选' },
              { code: 'filterSelect', name: '按所选单元格的值筛选' },
            ],
          },
          {
            code: 'sort',
            name: '排序',
            prefixIcon: 'vxe-icon-sort color-blue',
            children: [
              { code: 'clearSort', name: '清除排序' },
              { code: 'sortAsc', name: '升序', prefixIcon: 'vxe-icon-sort-alpha-asc color-orange' },
              { code: 'sortDesc', name: '倒序', prefixIcon: 'vxe-icon-sort-alpha-desc color-orange' },
            ],
          },
          { code: 'print', name: '打印', disabled: true },
        ],
      ],
    },
    footer: {
      options: [[{ code: 'clearAll', name: '清空数据' }]],
    },
  });

  const contextMenuClickEvent = ({ menu, row, column }) => {
    switch (menu.code) {
      case 'copy':
        // 示例
        if (row && column) {
          if (XEClipboard.copy(row[column.field])) {
            VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
          }
        }
        break;
      default:
        VXETable.modal.alert(`点击了 ${menu.name} 选项`);
    }
  };

  //选择叶子节点
  const selectLeaf = (selectedKeys, data) => {
    if (data.selectedNodes[0].title == '全部') {
      base.maType = '';
      base.topTwo = '';
      getTableData();
    } else if (!data.node.hasOwnProperty('children')) {
      base.maType = data.node.key.split('-')[1];
      base.topTwo = data.node.key.split('-')[0];
      getTableData();
    } else {
      base.maType = data.node.key;
      base.topTwo = '';
      getTableData();
    }
  };

  //获取表格数据
  const getTableData = () => {
    base.quickQuery = '';
    base.name = '';
    base.id = '';
    base.specification = '';
    base.shortcutCode = '';

    if (base.queryInfo) {
      if (base.type == 1) {
        base.quickQuery = base.queryInfo;
      } else if (base.type == 2) {
        base.name = base.queryInfo;
      } else if (base.type == 3) {
        base.id = base.queryInfo;
      } else if (base.type == 4) {
        base.specification = base.queryInfo;
      } else if (base.type == 5) {
        base.shortcutCode = base.queryInfo;
      }
    }

    const obj = {
      pageNum: base.pagination.current,
      pageSize: base.pagination.pageSize,
    };
    const steam = {
      id: base.id,
      maType: base.maType,
      topTwo: base.topTwo,
      name: base.name,
      shortcutCode: base.shortcutCode,
      specification: base.specification,
      quickQuery: base.quickQuery,
      customId: localStorage.getItem('customerId'),
    };

    invmbInvmabVoList(obj, steam).then((res: any) => {
      if (res.code == '200') {
        res.data.list.forEach((item) => {
          item.id = item.mb110;
        });
        base.tabelDom = res.data.list;
        base.pagination.total = res.data.total;
        getCheckedData();
      }
    });
  };

  //存储选中数据
  const storeData = () => {
    const obj = {
      selectionRows: base.selectionRows,
      source: 'ph',
    };
    localStorage.setItem('ITEMDOM', JSON.stringify(obj));
  };

  //全选或取消全选
  const selectAllChangeEvent = ({ checked, records }) => {
    const steamRtem: any = localStorage.getItem('ITEMDOM');
    let steamOpem: any = null;
    if (!isNullPm(steamRtem)) steamOpem = JSON.parse(steamRtem).selectionRows;
    if (isNullPm(steamOpem)) steamOpem = [];
    if (!(base.pagination.current - 1 in steamOpem)) {
      steamOpem.push(records);
    } else {
      steamOpem[base.pagination.current - 1] = records;
    }
    base.selectionRows = steamOpem;
    storeData();
  };

  //复选框事件
  const selectChangeEvent = ({ records }) => {
    const steamRtem: any = localStorage.getItem('ITEMDOM');
    let steamOpem: any = null;
    if (!isNullPm(steamRtem)) steamOpem = JSON.parse(steamRtem).selectionRows;
    if (isNullPm(steamOpem)) steamOpem = [];
    if (!(base.pagination.current - 1 in steamOpem)) {
      steamOpem.push(records);
    } else {
      steamOpem[base.pagination.current - 1] = records;
    }
    base.selectionRows = steamOpem;
    storeData();
  };

  //获取选中元素
  const getCheckedData = () => {
    const steamRtem: any = localStorage.getItem('ITEMDOM');
    let steamOpem: any = null;
    console.log(steamRtem);
    if (!isNullPm(steamRtem)) {
      base.selectedRowKeys = [];
      steamOpem = JSON.parse(steamRtem);
      steamOpem.selectionRows?.map((res: any) => {
        res.map((reb: any) => {
          base.selectedRowKeys.push(reb.id);
        });
      });
      base.selectionRows = steamOpem.selectionRows;
    }
  };

  //修改查询条件的提示语
  const changeQueryTip = () => {
    if (base.type == 1) {
      base.quickQueryTip = '请输入品名/品号/规格';
    } else {
      base.quickQueryTip = '';
    }
  };

  onMounted(() => {
    getAllClasses();
    getTableData();
  });

  return {
    base,
    treeData,
    menuConfig,
    contextMenuClickEvent,
    selectAllChangeEvent,
    selectChangeEvent,
    selectLeaf,
    getTableData,
    getMatchIndex,
    changeQueryTip,
  };
}
